﻿/*
 * @Author: wss 
 * @Date: 2020-10-21 15:57:42 
 * @Last Modified by:   wss 
 * @Last Modified time: 2020-10-21 15:57:42 
 */
using System.Collections;
using System.Collections.Generic;
using UnityEngine;


/// <summary>
/// 控制数量的进度条，适合一格格显示的HP条
/// </summary>
[AddComponentMenu("UI/Behavior/AmountBar")]
public class UIAmountBar : MonoBehaviour
{

    // 460 = 10个球
    // 420 = 9个球
    // 380 = 8个球
    // 340, =7个球
    // 300 , = 6个球
    // 260, = 5 个球
    // 220 = 4个球
    // 180 = 3个球

    public UISwitchChild amountSwitchChild;
    public UISwitchChild indexSwitchChild;

    public float minWidth = 100;
    public float offsetWidth = 40;

    public int maxCountLimit = 10;

    [SerializeField]
    private int _maxCount = 10;
    public int maxCount
    {
        get { return _maxCount; }
        set
        {
            if (_maxCount >= maxCountLimit) _maxCount = maxCountLimit;
            if (value < 0) value = 0;
            if (value != _maxCount)
            {
                _maxCount = value;
                UpdateMaxCountChange(value);
            }
        }
    }

    [SerializeField]
    private int _curCount = 10;
    public int curCount
    {
        get { return _curCount; }
        set
        {
            if (value >= _maxCount) value = _maxCount;
            if (value < 0) value = 0;
            if (value != _curCount)
            {
                _curCount = value;
                UpdateCurCountChange(value);
            }
        }
    }


    public Vector3 GetChildPosition(int index)
    {
        if (amountSwitchChild == null) return new Vector3();
        return amountSwitchChild.GetChildPosition(index);
    }

    private void UpdateMaxCountChange(int count)
    {
        amountSwitchChild.index = count;
        var rect = GetComponent<RectTransform>();
        rect.sizeDelta = new Vector2(minWidth + offsetWidth * count, rect.sizeDelta.y);
    }

    private void UpdateCurCountChange(int count)
    {
        indexSwitchChild.index = count;
    }


#if UNITY_EDITOR
    bool _flag = false;
    private void OnValidate()
    {
        if (_maxCount >= maxCountLimit) _maxCount = maxCountLimit;
        if (_maxCount < 0) _maxCount = 0;
        if (_curCount <= 0) _curCount = 0;
        _flag = true;
    }

    // Update is called once per frame
    void Update()
    {
        if (_flag)
        {
            _flag = false;
            UpdateMaxCountChange(_maxCount);
            UpdateCurCountChange(_curCount);
        }

    }
#endif


}
